import {Pipe, PipeTransform} from '@angular/core';
import {DocService} from '../service/doc.service';
import {EntityRef} from '../entity/entity-ref';
import {DocApi} from '../entity/doc-api';
import {StringUtils} from '../utils/string-utils';
import {ParamUtils} from '../utils/param-utils';

@Pipe({
    name: 'dubboApi'
})
export class DubboApiPipe implements PipeTransform {

    constructor(private docService: DocService) {
    }

    transform(api: DocApi, args?: any): any {
        return this.getDubboApi(api);
    }

    private getDubboApi(api: DocApi): String {
        if (!api) {
            return '';
        }
        const code = api.code;
        const sb = ['```java\n'];

        const index = code.lastIndexOf('.');

        sb.push('// ');
        sb.push(code.substr(0, index));
        sb.push('\n\n');

        const params: EntityRef[] = api.requestParams;
        const paramLen = params == null ? 0 : params.length;
        sb.push('/**');

        const name = api.name;
        if (name) {
            sb.push('\n * ');
            sb.push(name);
        }

        const comment: string = api.comment;
        if (comment && comment.length > 0) {
            sb.push('\n * ');
            sb.push(this.renderComment(comment));
        }
        sb.push('\n * ');
        if (params != null) {
            params.forEach((paramRef: EntityRef) => {
                sb.push('\n * @param ');
                sb.push(paramRef.name);
                sb.push(' ');
                sb.push(paramRef.comment);
            });
        }
        const resp: EntityRef = api.response;
        sb.push('\n * @return ');
        sb.push(resp.comment);
        sb.push('\n */\n');

        sb.push(StringUtils.toSimpleTypeName(resp.entityName));
        sb.push(' ');
        sb.push(code.substr(index + 1));
        sb.push('(');

        if (params != null) {
            const paramList = [];
            params.forEach((paramRef: EntityRef) => {
                paramList.push(`\t${ParamUtils.toStringWithAnnotation(paramRef)}`);
            });
            if (paramList.length > 0) {
                sb.push('\n');
                sb.push(paramList.join(',\n'));
                sb.push('\n');
            }
        }
        sb.push(');\n```');
        return sb.join('');
    }

    private renderComment(comment: string) {
        comment = comment.replace(/\n/g, '\n *');
        return comment;
    }
}
